var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const expressJwt = require('express-jwt')

var indexRouter = require('./routes/index');
var admin = require('./routes/admin');

// var history = require('connect-history-api-fallback');

var app = express();

// app.use(history());

const cors = require('cors');
app.use(cors());
// swagger
var swaggerUi = require('swagger-ui-express');
var swaggerJSDoc = require('swagger-jsdoc');

var swaggerDefinition = {
  info: {
    title: '个人博客接口包含三端',
    version: '1.0.0',
    description: '个人博客接口包含三端',
  },
  host: '',
  basePath: '',
};

// options for the swagger docs
var options = {
  // import swaggerDefinitions
  swaggerDefinition: swaggerDefinition,
  // path to the API docs
  apis: ['./routes/*.js'],
  authAction: { JWT: { name: "JWT", schema: { type: "apiKey", in: "header", name: "Authorization", description: "" }, value: "Bearer <JWT>" } }
};

// initialize swagger-jsdoc
var swaggerSpec = swaggerJSDoc(options);

// serve swagger
app.get('/swagger.json', function (req, res) {
  res.setHeader('Content-Type', 'application/json');
  res.send(swaggerSpec);
});

app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));
var http = require('http');
var server = http.createServer(app);

// jwt设置
app.use(expressJwt({
  secret: 'jiao1030',  // 签名的密钥 或 PublicKey
  algorithms: ["HS256"]
}).unless({
  path: ['/admin/login', '/api/feblog/getArticleList', '/api/feblog/getArticleById', '/api/feblog/getArticleType']  // 指定路径不经过 Token 解析
}))

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/admin', admin);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

server.listen('3001', () => {
  console.log('http://127.0.0.1:3001')
})
